package com.qf.util;

import com.qf.dao.impl.UsersDaoImpl;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * 2019/11/13
 * Administrator
 * spring_proxy
 * 面向对象面向君  不负代码不负卿
 */
//  Interceptor 拦截器
public class CglibUtils implements MethodInterceptor {
     //要生成代理类的对象
    private UsersDaoImpl daoImpl;

    public CglibUtils(UsersDaoImpl daoImpl) {
        this.daoImpl = daoImpl;
    }

    //创建代理对象的方法
    public UsersDaoImpl createProxy(){
        Enhancer enhancer=new Enhancer();
        enhancer.setSuperclass(daoImpl.getClass());
        enhancer.setCallback(this);//callback回调
        UsersDaoImpl impl=(UsersDaoImpl) enhancer.create();//创建代理对象
        return impl;
    }

    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        //定义代理类需要做的事情
        System.out.println("代理开始执行");
        Object invoke = methodProxy.invokeSuper(o,objects);
        System.out.println("代理结束执行");
        return invoke;
    }
}
